// 首先需要安装vuex: 运行命令 'npm install vuex'
import { createStore } from 'vuex';

export default createStore({
  state: {
    isAuthenticated: false, // 用户是否已认证
    userRole: 'student', // 用户角色，默认为学生
    activities: [] // 活动列表
  },
  mutations: {
    // 设置认证状态
    SET_AUTH(state, authStatus) {
      state.isAuthenticated = authStatus;
    },
    // 设置用户角色
    SET_USER_ROLE(state, role) {
      state.userRole = role;
    },
    // 设置活动数据
    SET_ACTIVITIES(state, activities) {
      state.activities = activities;
    },
    // 添加新活动
    ADD_ACTIVITY(state, activity) {
      state.activities.push(activity);
    },
    // 更新活动
    UPDATE_ACTIVITY(state, updatedActivity) {
      const index = state.activities.findIndex(a => a.id === updatedActivity.id);
      if (index !== -1) {
        state.activities.splice(index, 1, updatedActivity);
      }
    },
    // 删除活动
    DELETE_ACTIVITY(state, id) {
      const index = state.activities.findIndex(a => a.id === id);
      if (index !== -1) {
        state.activities.splice(index, 1);
      }
    }
  },
  actions: {
    // 登录操作
    login({ commit }, username) {
      commit('SET_AUTH', true);
      commit('SET_USER_ROLE', username === 'admin' ? 'admin' : 'student');
    },
    // 登出操作
    logout({ commit }) {
      commit('SET_AUTH', false);
      commit('SET_USER_ROLE', 'student');
    },
    // 加载活动数据
    loadActivities({ commit }) {
      // 这里应该从activities.json文件加载数据
      // 由于示例数据在需求文档中，我们直接使用这些数据
      const activities = [
        {
          id: 1,
          title: "校园运动会",
          description: "本次运动会包含多种田径项目和球类项目，欢迎同学们积极参与！",
          date: "2025-05-10",
          location: "学校操场"
        },
        {
          id: 2,
          title: "科技讲座",
          description: "邀请知名科技专家分享前沿科技知识，拓宽同学们的科技视野。",
          date: "2025-05-15",
          location: "学校礼堂"
        },
        {
          id: 3,
          title: "文化艺术展览",
          description: "展示学生们的绘画、书法、摄影等艺术作品，感受艺术的魅力。",
          date: "2025-05-20",
          location: "学校艺术展厅"
        }
      ];
      commit('SET_ACTIVITIES', activities);
    },
    // 添加活动
    addActivity({ commit, state }, activity) {
      // 生成新的ID（这里只是一个简单的方法，实际应用应更可靠）
      const newId = Math.max(...state.activities.map(a => a.id), 0) + 1;
      const activityWithId = { ...activity, id: newId };
      commit('ADD_ACTIVITY', activityWithId);
    },
    // 更新活动
    updateActivity({ commit }, activity) {
      commit('UPDATE_ACTIVITY', activity);
    },
    // 删除活动
    deleteActivity({ commit }, id) {
      commit('DELETE_ACTIVITY', id);
    }
  },
  getters: {
    // 获取所有活动
    getAllActivities: state => state.activities,
    // 根据ID获取活动
    getActivityById: state => id => state.activities.find(activity => activity.id === parseInt(id)),
    // 获取用户角色
    getUserRole: state => state.userRole,
    // 是否已认证
    isAuthenticated: state => state.isAuthenticated
  }
});